package com.github.pig.admin.controller.zhgl.unit;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.admin.model.device.GuardDevice;
import com.github.pig.admin.model.zhgl.unit.BuildingUnit;
import com.github.pig.admin.service.device.IGuardDeviceService;
import com.github.pig.admin.service.zhgl.unit.IBuildingUnitService;
import com.github.pig.admin.util.AjaxJson;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.IdGenerate;
import com.github.pig.common.util.R;
import com.github.pig.common.web.BaseController;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.*;

/**
 * <p>
 * ���ݻ�����Ϣ 前端控制器
 * </p>
 *
 * @author xiaosa
 * @since 2018-06-04
 */
@Controller
@RequestMapping("/buildingUnit")
public class BuildingUnitController extends BaseController {

    @Autowired
    private IBuildingUnitService buildingUnitService;
    @Autowired
    private IGuardDeviceService guardDeviceService;

    /**
    * 通过ID查询
    *
    * @param id ID
    * @return CommunityBuilding
    */
    @GetMapping("/{id}")
    public R<BuildingUnit> get(@PathVariable Integer id) {
        return new R<>(buildingUnitService.selectById(id));
    }

    /**
    * 分页查询信息
    *
    * @param params 分页对象
    * @return 分页对象
    */
    @RequestMapping("/page")
    @ResponseBody
    public Page page(@RequestParam Map<String, Object> params, BuildingUnit buildingUnitWhere) {
        EntityWrapper entityWrapper = new EntityWrapper<BuildingUnit>();
        Page<BuildingUnit> page = new Page<BuildingUnit>(Integer.parseInt(params.getOrDefault("page", 1).toString())
                , Integer.parseInt(params.getOrDefault("limit", 10).toString()));
        //拼装条件
        initCondition(params,entityWrapper,buildingUnitWhere);
        return buildingUnitService.selectPage(page, entityWrapper.orderBy("sort",true));
    }

    private void initCondition(Map<String, Object> params, EntityWrapper entityWrapper, BuildingUnit buildingUnitWhere) {
        entityWrapper.eq("del_flag", CommonConstant.STATUS_NORMAL);
        if(StringUtils.isNotEmpty(buildingUnitWhere.getUnitName())){
            entityWrapper.like("unit_name",buildingUnitWhere.getUnitName());
        }
        if(StringUtils.isNotEmpty(buildingUnitWhere.getBuildingId())){
            entityWrapper.eq("building_id",buildingUnitWhere.getBuildingId());
        }
        entityWrapper.setSqlSelect("id, building_id AS buildingId,(select building_name from community_building where id=building_id) AS buildingName, unit_name AS unitName, cleaning_user AS cleaningUser, safe_user AS safeUser, del_flag AS delFlag,sort");
    }

    /**
     * 添加
     * @param  buildingUnit  实体
     * @return success/false
     */
    @RequestMapping("/doAdd")
    @ResponseBody
    public R<Boolean> add(@RequestBody BuildingUnit buildingUnit) {
        R r = new R();
        buildingUnit.setDelFlag(CommonConstant.STATUS_NORMAL);
        if(existUnit(buildingUnit.getBuildingId(),buildingUnit.getUnitName(),null)){
            r.setMsg("单元名重复");
            r.setData(false);
            return r;
        }
        buildingUnitService.insert(buildingUnit);
        //保存开锁信息
        GuardDevice g = new GuardDevice();
        g.setGuardId(IdGenerate.getUUID());
        g.setCommunityId(buildingUnit.getCommunityId());//当前社区ID
        g.setGuardId(buildingUnit.getId()); //当前社区或楼宇或单元ID
        g.setGuardPid(buildingUnit.getBuildingId());//当前社区或楼宇或单元的上级ID，如果是顶级，此处填字符串 0
        g.setDeviceType("unit");
        g.setDeviceName(buildingUnit.getUnitName());
        g.setCreateTime(new Date());
        g.setUpdateTime(new Date());
        g.setDelFlag(CommonConstant.STATUS_NORMAL);
        r.setData(guardDeviceService.insert(g));
        return r;
    }

    /**
     * 判断是否存在重复单元
     * @param buildingId
     * @return
     */
    public boolean existUnit(String buildingId,String unitName,String id){
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("building_id",buildingId);
        entityWrapper.eq("unit_name",unitName);
        if(StringUtils.isNotEmpty(id)){
            //说明是修改
            entityWrapper.ne("id",id);
        }
        entityWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        List list = buildingUnitService.selectList(entityWrapper);
        if(list!=null&&list.size()>0){
            return true;
        }
        return false;
    }

    /**
     * 删除
     * @param id ID
     * @return success/false
     */
    @RequestMapping("/doDel")
    @ResponseBody
    public AjaxJson delete( String id) {
        AjaxJson json=new AjaxJson();
        BuildingUnit buildingUnit = buildingUnitService.selectById(id);
        buildingUnit.setDelFlag(CommonConstant.STATUS_DEL);
        boolean flag = buildingUnitService.updateById(buildingUnit);
        json.setSuccess(flag);
        if(flag){
            json.setMsg("删除成功!");

        }else{
            json.setMsg("删除失败!");
        }
        return json;
    }

    @RequestMapping("/doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids){
        AjaxJson json=new AjaxJson();
        List<BuildingUnit> list = buildingUnitService.selectBatchIds(Arrays.asList(ids.split(",")));
        for(BuildingUnit bean : list){
            bean.setDelFlag(CommonConstant.STATUS_DEL);
        }
        boolean flag = buildingUnitService.updateBatchById(list);
        json.setSuccess(flag);
        if(flag){
            json.setMsg("删除成功!");

        }else{
            json.setMsg("删除失败!");
        }
        return json;
    }

    /**
     * 编辑
     * @param  buildingUnit  实体
     * @return success/false
     */
    @RequestMapping("/doUpdate")
    @ResponseBody
    public R<Boolean> edit(@RequestBody BuildingUnit buildingUnit) {
        R r = new R();
        if(existUnit(buildingUnit.getBuildingId(),buildingUnit.getUnitName(),buildingUnit.getId())){
            r.setMsg("单元名重复");
            r.setData(false);
            return r;
        }
        r.setData(buildingUnitService.updateById(buildingUnit));
        return r;
    }


}
